package com.qianya.system.manage.web.login.controller;

import cn.hutool.core.util.IdUtil;
import com.qianya.model.common.CommonResult;
import com.qianya.model.common.JWTUtil;
import com.qianya.model.common.ResultCode;
import com.qianya.model.pojo.login.qo.LoginQO;
import com.qianya.model.pojo.login.qo.LoginUsersQO;
import com.qianya.model.pojo.login.qo.LoginVO;
import com.qianya.model.pojo.login.vo.LoginRoleVO;
import com.qianya.model.pojo.login.vo.LoginUsersPermissionVO;
import com.qianya.model.pojo.login.vo.LoginUsersVO;
import com.qianya.system.manage.config.RedisUtil;
import com.qianya.system.manage.util.password.PasswordUtil;
import com.qianya.system.manage.web.login.service.ILoginRoleService;
import com.qianya.system.manage.web.login.service.ILoginUsersPermissionService;
import com.qianya.system.manage.web.login.service.ILoginUsersService;
import com.qianya.system.manage.web.sys.model.SysConfig;
import com.qianya.system.manage.web.sys.model.SysLog;
import com.qianya.system.manage.web.sys.service.ISysConfigService;
import com.qianya.system.manage.web.sys.service.ISysLogService;
import com.qianya.util.BaseCommon;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.catalina.connector.Request;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.qianya.system.manage.web.login.controller
 * @ClassName: LoginController
 * @Author: zzq
 * @Description:
 * @Date: 2020/7/3 9:39
 * @Version: 1.0
 */
@RestController
@Api(value = "LoginController", tags = "登录接口")
@RequestMapping("/logins")
@Validated
public class LoginController {

    /**
     * 引入用户服务
     */
    @Autowired
    private ILoginUsersService loginUsersService;
    @Resource
    ISysLogService iSysLogService;

    @Resource
    private ISysConfigService sysConfigService;


    @Autowired
    private ILoginUsersPermissionService iLoginUsersPermissionService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public CommonResult<LoginVO> login(@Valid @RequestBody LoginQO loginQO) {

        //对修改的密码加密
        String s = PasswordUtil.encodePassword(loginQO.getUPassword());
        //存入对象
        loginQO.setUPassword(s);
        LoginUsersQO loginUsersQO = new LoginUsersQO();
        BeanUtils.copyProperties(loginQO, loginUsersQO);
        Object num = RedisUtil.get("login" + loginUsersQO.getUUsername());
        SysConfig sysConfig = (SysConfig) sysConfigService.find().getBean();
        if (num!=null){
            Integer count =(Integer) num;
            if (count > sysConfig.getSetLoginFailLimit()) {
                return CommonResult.error(ResultCode.ERROR, "请" + sysConfig.getSetLoginTimeLimit() + "分钟之后再登录");
            }
        }
        //获取用户
        LoginUsersVO loginUsersVO = loginUsersService.login(loginUsersQO);

        //如果没有获取到用户，表示用户名或密码错误
        if (loginUsersVO == null) {
            //得到用户名
            String uUsername = loginUsersQO.getUUsername();
            Object obj = RedisUtil.get("login" + uUsername);

            if (obj == null) {
                RedisUtil.set("login" + uUsername, 1, sysConfig.getSetLoginTimeLimit() * 60);
                return CommonResult.error(ResultCode.ERROR, "账号密码错误");
            }
            else {
                Integer count =(Integer) obj;
                if (count > sysConfig.getSetLoginFailLimit()) {
                    return CommonResult.error(ResultCode.ERROR, "请" + sysConfig.getSetLoginTimeLimit() + "分钟之后再登录");
                }
                count++;
                RedisUtil.set("login" + uUsername, count, sysConfig.getSetLoginTimeLimit() * 60);
                return CommonResult.error(ResultCode.ERROR, "账号密码错误");
            }

        }
        if(loginUsersVO.getUStatus()==1){
            return CommonResult.error(ResultCode.ERROR, "该账户已被禁用");
        }
        //获取用户权限
        List<LoginUsersPermissionVO> loginUsersPermissionVOList = iLoginUsersPermissionService.find(loginQO.getUUsername(), 1);
        Map<String, Object> map = new HashMap<String, Object>(64);
        //将权限从用户中取出来
        for (LoginUsersPermissionVO loginUsersPermissionVO : loginUsersPermissionVOList) {
            map.put(loginUsersPermissionVO.getPUrl(), 1);
        }
        RedisUtil.removeObject("Role:" + loginUsersVO.getUUsername());
        //将角色缓存到redis中
        RedisUtil.hset("Role:" + loginUsersVO.getUUsername(), map);
        //生成token
        String token = JWTUtil.createToken(loginUsersVO);
        SysLog sysLog1 = new SysLog();
        sysLog1.setId(IdUtil.simpleUUID());
        sysLog1.setUserid(loginUsersVO.getUId());
        sysLog1.setUsername(loginUsersVO.getUUsername());
        BaseCommon baseCommon = new BaseCommon();
        HttpServletRequest request = baseCommon.getRequest();
        sysLog1.setLogType(loginUsersVO.getUType());
        sysLog1.setResult("登录成功");
        iSysLogService.create(sysLog1, request);
        //返回token跟用户id
        return CommonResult.success(new LoginVO(token, loginUsersVO.getUId()));
    }

    @PostMapping("/refreshToken")
    @ApiOperation(value = "刷新Token")
    public CommonResult refreshToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = JWTUtil.refreshToken(request.getHeader("token"));
        return CommonResult.success(token);
    }
}
